package com.xhapi.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhapi.pojo.dto.DiaryDTO;
import com.xhapi.pojo.entity.ApiResult;
import com.xhapi.pojo.entity.UserDiary;
import com.xhapi.service.IUserDiaryService;
import com.xhapi.utils.ApiResultHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * <p>
 * 用户日记表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-05-08
 */
@RestController
@Slf4j
@RequestMapping("/user-diary")
@RequiredArgsConstructor
@CrossOrigin
public class UserDiaryController {
    /*
    * 本接口提供es功能，如果使用请删除增删改方法体内的注释并且使用es查询接口
    * */
    private final IUserDiaryService iUserDiaryService;
    //新增一个日记
    @PostMapping
    public ApiResult addDiary(@RequestBody UserDiary userDiary) throws IOException {
        iUserDiaryService.save(userDiary);
        //iUserDiaryService.add(userDiary);
        return ApiResultHandler.success();
    }
    //删除一个日记
    @DeleteMapping
    public ApiResult deleteDiary(@RequestParam Integer id) throws IOException {
        iUserDiaryService.removeById(id);
        //iUserDiaryService.delete(id);
        return ApiResultHandler.success();
    }
    //更新一个日记
    @PutMapping
    public ApiResult updateDiary(@RequestBody UserDiary userDiary) throws IOException {
        iUserDiaryService.updateById(userDiary);
        //iUserDiaryService.add(userDiary);
        return ApiResultHandler.success();
    }
    //分页查询所有自己的日记
    @GetMapping
    public ApiResult findDiary(@RequestParam Integer userId, @RequestParam Integer pageNo, @RequestParam Integer pageSize){
        log.info(userId + "-" + pageNo + "-" + pageSize);
        // 分页查询
        Page<UserDiary> result = iUserDiaryService.lambdaQuery()
                .eq(UserDiary::getUserId, userId)
                .orderByAsc(UserDiary::getDiaryDate)
                .page(new Page(pageNo, pageSize));

        return ApiResultHandler.success(result);
    }
    // es分页查询，提高高级模糊查询
    @GetMapping("/es")
    public ApiResult findDiaryByEs(@RequestParam Integer userId, @RequestParam String keyword,
                                   @RequestParam Integer pageNo, @RequestParam Integer pageSize) throws IOException {
        return ApiResultHandler.success(iUserDiaryService.search(userId, keyword, pageNo, pageSize));
    }
}
